package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LoginInterceptor
 * Package:
 * Description:
 *
 * @Author pupu
 * @Create 2025/9/10 16:36
 * @Version 1.0
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {


    private RedisTemplate<String, Object> redisTemplate;

    public RefreshTokenInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登录拦截器逻辑
        // 1.获取请求头中的token
        String token = request.getHeader("authorization");
        if(StringUtils.isBlank(token)){

            return true;
        }

        // 基于token获取redis中的用户
        String key = RedisConstants.LOGIN_USER_KEY + token;

        Map<Object, Object> userMap = redisTemplate.opsForHash().entries(key);
        //3.如果没有，则拦截
        if (userMap.isEmpty()) {

            return true;
        }
        //将查询到的hashmap对象转为userDTO对象，并保存到ThreadLocal中
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //4.如果有，则保存到ThreadLocal中
        UserHolder.saveUser(userDTO);
        // 刷新token有效期
        redisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //5.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();

    }
}
